import config from "../config.js"

let websocket = {}

// 服务器接口地址
websocket.url = config.wss
// 链接是否打开
websocket.isSocketOpen = false
// 心跳定时，每30s执行一次
websocket.timer = ''
// 每Xs执行一次心跳数据发送
websocket.seconds = 30

/**
 * 创建链接并监听打开&报错事件&关闭事件
 * @date 2022-05-17
 */
websocket.init = function() {
	return new Promise((resolve, reject) => {
		// 创建一个 WebSocket 连接。
		uni.connectSocket({
			url: this.url,
			header: {
				'Access-Control-Allow-Origin' : '*'
			},
			success: (res) => {
				console.log('connectSocketSuccess', res)
			},
			fail: (res) => {
				console.log('connectSocketFail', res)
			},
			complete: (res) => {
				// console.log('connectSocketComplete', res)
			}
		})

		// 监听WebSocket连接打开事件
		uni.onSocketOpen((res) => {
			console.log('onSocketOpen', res)

			this.isSocketOpen = true

			// 发送心跳数据
			this.timer = setInterval(() => {
				this.sendMessage({
					type: 'heart_beat',
					send_type: 'to_self',
					data: {
						content: '发送心跳数据'
					}
				})
			}, this.seconds * 1000)

			resolve(res)
		})

		// 监听WebSocket错误
		uni.onSocketError((res) => {
			console.log('onSocketError', res)
			reject(res)
		})

		// 监听WebSocket关闭
		uni.onSocketClose((res) => {
			console.log('onSocketClose', res)
			this.isSocketOpen = false

			// 关闭心跳
			if (this.timer) {
				clearInterval(this.timer)
			}
			
			// clientId移除缓存
			uni.removeStorageSync('clientId')
			reject(res)
		})
	})
}

/**
 * 通过 WebSocket 连接发送数据
 * @date 2022-05-18
 */
websocket.sendMessage = function(data) {
	return new Promise((resolve, reject) => {
		if (!this.isSocketOpen) {
			reject('当前websocket连接未打开')
			return false
		}
		uni.sendSocketMessage({
			data: JSON.stringify(data),
			success: (res) => {
				console.log('sendMessageSuccess', res)
				resolve(res)
			},
			fail: (res) => {
				console.log('sendMessageFail', res)
				reject(res)
			}
		})
	})
}

/**
 * 关闭 WebSocket 连接
 * @date 2022-05-18
 */
websocket.closeSocket = function() {
	// 更改websocket状态为关闭
	this.isSocketOpen = false

	uni.closeSocket()
}

export default websocket
